﻿using FastEndpoints;
using System.Reflection;
using vite_core.Common;
using vite_entity.Entities;
using vite_services;

namespace vite_net.Common.Filters
{
    public class ViteNetGlobalPreProcessor : IGlobalPreProcessor
    {
        public async Task PreProcessAsync(IPreProcessorContext ctx, CancellationToken ct)
        {
            var logger = ctx.HttpContext.Resolve<ILogger<ViteNetGlobalPreProcessor>>();
            var requestStr = string.Empty;
            if (ctx.Request is not EmptyRequest)
            {
                var thisRequest = ctx.Request;
                Type type = thisRequest.GetType();
                PropertyInfo[] properties = type.GetProperties();
                requestStr = "请求路径：" + ctx.HttpContext.GetEndpoint() + ";请求参数：" + string.Join(",", properties.Select(x => x.Name + ":"+ x.GetValue(thisRequest)));
            }
            var _systemServices = ctx.HttpContext.Resolve<SystemServices>();
            var sysLog = new SysLog()
            {
                Module = "OTHER",
                Browser = "",// ctx.HttpContext.Request.Headers["User-Agent"].ToString().Substring(0,100),
                BrowserVersion = "",
                Content = requestStr,
                CreateBy = long.TryParse(ctx.HttpContext.User.FindFirst(SysConstant.LogClaimUserId)?.Value, out long userId) ? userId : 0,
                CreateTime = DateTime.Now,
                ExecutionTime = 1,
                Ip = ctx.HttpContext.Request.Host.Host,
                Province = "",
                City = "",
                Os = "",
                RequestUri = ctx.HttpContext.Request.Host.ToString()
            };
            await _systemServices.AddLogAsync(sysLog);

        }
    }

    // todo
    public class ViteNetGlobalPostProcessor : IGlobalPostProcessor
    {
        public async Task PostProcessAsync(IPostProcessorContext context, CancellationToken ct)
        {
            context.HttpContext.GetEndpoint();
        }
    }

}
